﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace WaiShop.Core
{
    public class HttpHelper
    {
        /// <summary>
		/// GET数据
		/// </summary>
		/// <param name="url"></param>
		/// <returns></returns>
		public static string Get(string url)
        {
            string text = "";
            char[] array = new char[256];
            Stream responseStream = ((HttpWebResponse)((HttpWebRequest)WebRequest.Create(new Uri(url))).GetResponse()).GetResponseStream();
            StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8);
            for (int length = streamReader.Read(array, 0, 256); length != 0; length = streamReader.Read(array, 0, 256))
            {
                string str = new string(array, 0, length);
                text += str;
            }
            if (responseStream != null)
            {
                responseStream.Close();
            }
            return text;
        }


        /// <summary>
        /// 支持json的post请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="data"></param>
        /// <returns></returns>
		public static string PostJson(string url, string data)
        {
            StringBuilder stringBuilder = new StringBuilder();
            if (string.IsNullOrEmpty(url))
            {
                throw new Exception("无效的Url");
            }
            WebRequest webRequest = WebRequest.Create(url);
            webRequest.Method = "POST";
            byte[] bytes = Encoding.UTF8.GetBytes(data);
            webRequest.ContentType = "application/json; charset=UTF-8";
            webRequest.ContentLength = (long)bytes.Length;
            string text;
            using (Stream requestStream = webRequest.GetRequestStream())
            {
                requestStream.Write(bytes, 0, bytes.Length);
                using (WebResponse response = webRequest.GetResponse())
                {
                    using (Stream responseStream = response.GetResponseStream())
                    {
                        using (StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8))
                        {
                            text = streamReader.ReadToEnd();
                        }
                    }
                }
            }
            return text;
        }
    }
}
